import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

export interface News {
  id: number;
  title: string;
  content: string;
  coverUrl: string;
  createTime: string;
}

export const newsFields = [
  { key: 'title', label: '标题', type: 'text', placeholder: '请输入新闻标题', maxLength: 100, },
  { key: 'content', label: '内容', type: 'textarea', placeholder: '请输入新闻内容', maxLength: 1000, },
  { key: 'coverUrl', label: '封面图片', type: 'image', placeholder: '请上传封面图片', }, ];

export const useNewsStore = defineStore('news', {
  state: () => ({
    newsList: [] as News[],
  }),

  actions: {
    async fetchNewsList() {
      try {
        const response = await axios.get('/news');
        return response.data.data || [];
      } catch (error) {
        throw new Error('获取新闻列表失败');
      }
    },

    async createNews(data: Omit<News, 'id' | 'createTime'>) {
      const response = await axios.post('/news', data);
      return response.data.data;
    },

    async updateNews(data: News) {
      const response = await axios.put('/news', data);
      return response.data.data;
    },

    async deleteNews(id: number) {
      await axios.delete(`/news/${id}`);
    },

    async uploadCover(file: File) {
      const formData = new FormData();
      formData.append('file', file);
      const response = await axios.post('/file', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      return response.data.data.url;
    },

    // 获取单个新闻
    async fetchNewsById(id: number) {
      try {
        const response = await axios.get(`/news/${id}`);
        if (response.data.code === 200) {
          const news = response.data.data as News;
          console.log('NewsStore: Fetched news:', news);
          return news;
        }
        throw new Error(response.data.message || '获取新闻失败');
      } catch (error: any) {
        console.error('NewsStore: 获取新闻失败:', error);
        return null;
      }
    },

    async searchNews(query: string) {
      try {
        const response = await axios.get('/news/search', {
          params: { q: query },
        });
        if (response.data.code === 200) {
          const results = response.data.data as News[];
          console.log('NewsStore: Searched news:', results);
          return results;
        }
        throw new Error(response.data.message || '搜索新闻失败');
      } catch (error: any) {
        console.error('NewsStore: 搜索新闻失败:', error);
        return [];
      }
    },
  },
});
